package leetcode;

import java.util.ArrayList;
import java.util.List;

//复原ip地址
public class RestoreIpAddresses {
    public static void main(String[] args) {
        RestoreIpAddresses restoreIpAddresses = new RestoreIpAddresses();
        List<String> strings = restoreIpAddresses.restoreIpAddresses("0279245587303");
        strings.stream().forEach(System.out::println);
        //System.out.println(restoreIpAddresses.isIpAddress("255.25.51.1135"));
    }
    public List<String> restoreIpAddresses(String s) {
        List<String> list = new ArrayList<>();
        int n = s.length();
        if(n <4){
            return list;
        }
        //往s中插入3个. 形成新的字符串 判断新的字符串是不是合法ip 是则加入集合
        for (int i = 0;i<3;i++){
            for (int j =i+1;j<6;j++){
                if(j>=n) break;
                for (int k = j+1;k<9;k++){
                    if(k>=n -1) break;
                    if(n-k>4) continue;
                    String s1 = s.substring(0,i+1) + "." + s.substring(i+1,j+1) + "." + s.substring(j+1,k+1) + "." + s.substring(k+1,n);
                    if(isIpNums(s.substring(0,i+1)) && isIpNums(s.substring(i+1,j+1)) && isIpNums(s.substring(j+1,k+1)) && isIpNums(s.substring(k+1,n))){
                        list.add(s1);
                    }
/*
                    if(isIpAddress(s1)){
                        list.add(s1);
                    }*/
                }
            }
        }
        return list;
    }
    public boolean isIpNums(String s){
        if(s.length()>3) return false;
        if(s.charAt(0) == '0' && s.length()>1){
            return false;
        }
        return Integer.parseInt(s) <= 255 && Integer.parseInt(s) >= 0;
    }
    public  boolean isIpAddress(String s){
        int n = s.length();
        if(n<6){
            return false;
        }
        int pre = 0;
        int cur = 0;
        while(cur<n){
            if(s.charAt(cur) != '.'){
                cur++;
                if(cur == n-1){
                    if(s.charAt(pre) == '0' && cur - pre>1 || cur == pre || cur - pre >3){
                        return false;
                    }
                    int i = Integer.parseInt(s.substring(pre, cur + 1));
                    if(i< 0 || i>255){
                        return false;
                    }
                }
            }else{
                if(s.charAt(pre) == '0' && cur - pre>1 || cur == pre || cur - pre >3){
                    return false;
                }else {
                    int i = Integer.parseInt(s.substring(pre, cur));
                    if(i< 0 || i>255){
                        return false;
                    }
                    pre = cur +1;
                    cur++;
                }
            }
        }
        return true;
    }
}
